<!DOCTYPE html>
<html>

<head>
  
  <title>lucene6.6.0学习心得 | 布.</title>
  <meta name="google-site-verification" content="" />
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta itemprop="name" content="布." />
  <meta itemprop="description" content="漫长岁月" />
  <meta itemprop="image" content="" />
  <link rel="shortcut icon" href="" type="image/x-icon">
  <!-- keywords and description -->
  
  <meta name="keywords" content="" />
  <meta name="description" content="" />
  
  
<link rel="stylesheet" href="/css/style.css">

  <script src="//cdn.jsdelivr.net/npm/@waline/client/dist/Waline.min.js"></script>
<meta name="generator" content="Hexo 6.0.0"></head>

<body>
  <div id="container">
    <header>
  <div class="site-title">
    <a href="/">
      布.
    </a>
  </div>
  
  <div class="site-subtitle">
    漫长岁月
  </div>
  
  
  <p class="links">
    
    <a target="_blank" rel="noopener" href="https://blog.csdn.net/qq_29485177">
      <img src="/images/links/link.png" alt="CSDN">
    </a>
    
  </p>
  
</header>
    <div id="main">
      <article class="post">
  <h3 class="date">
  <time datetime="2015-10-31T16:00:00.000Z">
    Nov 1, 2015
  </time>
</h3>
  <h1>lucene6.6.0学习心得</h1>
  <p class="post-info">
  
  
</p>
  
  
  <article>
    <h2 id="lucene是什么？"><a href="#lucene是什么？" class="headerlink" title="lucene是什么？"></a>lucene是什么？</h2><p>官方网站：使用Java语言编写的高性能全文检索工程。适合任何需要全文检索的应用，特别是跨平台的。<br>本菜鸟：空间换速度，查的快，毫秒级查询，秒杀like！</p>
<h2 id="导入依赖"><a href="#导入依赖" class="headerlink" title="导入依赖"></a>导入依赖</h2><pre><code>&lt;dependency&gt;
    &lt;groupId&gt;org.apache.lucene&lt;/groupId&gt;
    &lt;artifactId&gt;lucene-core&lt;/artifactId&gt;
    &lt;version&gt;6.6.0&lt;/version&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
    &lt;groupId&gt;org.apache.lucene&lt;/groupId&gt;
    &lt;artifactId&gt;lucene-analyzers-common&lt;/artifactId&gt;
    &lt;version&gt;6.6.0&lt;/version&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
    &lt;groupId&gt;org.apache.lucene&lt;/groupId&gt;
    &lt;artifactId&gt;lucene-analyzers-smartcn&lt;/artifactId&gt;
    &lt;version&gt;6.6.0&lt;/version&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
    &lt;groupId&gt;org.apache.lucene&lt;/groupId&gt;
    &lt;artifactId&gt;lucene-queryparser&lt;/artifactId&gt;
    &lt;version&gt;6.6.0&lt;/version&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
    &lt;groupId&gt;org.apache.lucene&lt;/groupId&gt;
    &lt;artifactId&gt;lucene-highlighter&lt;/artifactId&gt;
    &lt;version&gt;6.6.0&lt;/version&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
    &lt;groupId&gt;org.apache.lucene&lt;/groupId&gt;
    &lt;artifactId&gt;lucene-memory&lt;/artifactId&gt;
    &lt;version&gt;6.6.0&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
<h2 id="创建索引"><a href="#创建索引" class="headerlink" title="创建索引"></a>创建索引</h2><p>lucene将需要进行检索的内容经过指定的分词器（Analyzer）分词后存为索引（一般存在文件系统FSDirectory，也可以是内存RAMDirectory）。</p>
<pre><code>String indexPath = &quot;D:/index&quot;; 
//得到索引存放目录对象
Directory dir = FSDirectory.open(Paths.get(indexPath, new String[0]));
//这个是官方的中文分词器，还有其他MMAnalyzer、IkAnalyzer等
SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer();
//索引写入类需要的配置类
IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
//索引写入类
IndexWriter iw = new IndexWriter(dir, iwc);

//User:&#123;Integer id,String name,String sign&#125;
List&lt;User&gt; userList = new ArrayList&lt;User&gt;();
userList.add(new User(1,&quot;老大&quot;,&quot;我是我们家的大哥大！&quot;));
userList.add(new User(2,&quot;老二&quot;,&quot;我是呆萌的二哈！&quot;));
userList.add(new User(3,&quot;老三&quot;,&quot;我是专门拆散家庭人人讨厌的小三！&quot;));
userList.add(new User(4,&quot;老四&quot;,&quot;我是小可爱！&quot;));

for(User user : userList)&#123;
    //document类似数据库的table
    Document doc = new Document();
    //Field类似数据库的column
    doc.add(new StoredField(&quot;id&quot;,user.getId()));
    doc.add(new StringField(&quot;name&quot;,user.getName(),Field.store.YES));
    doc.add(new TextField(&quot;sign&quot;,user.getSign(),Field.store.YES));
    iw.addDocument(doc);
&#125;

//创建索引完成，关闭索引写入类
iw.close();
</code></pre>
<h4 id="各种Field类"><a href="#各种Field类" class="headerlink" title="各种Field类"></a>各种Field类</h4><table>
<thead>
<tr>
<th>名称</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>TextField</td>
<td>分词并存入索引</td>
</tr>
<tr>
<td>StringField</td>
<td>逐字的存为索引</td>
</tr>
<tr>
<td>IntPoint</td>
<td>Int类型存为索引以提供精确&#x2F;范围查询</td>
</tr>
<tr>
<td>LongPoint</td>
<td>Long类型存为索引以提供精确&#x2F;范围查询</td>
</tr>
<tr>
<td>DoublePoint</td>
<td>DoublePoint类型存为索引以提供精确&#x2F;范围查询</td>
</tr>
<tr>
<td>SortedDocValuesField</td>
<td>String类型存为索引以提供排序</td>
</tr>
<tr>
<td>SortedSetDocValuesField</td>
<td>String类型的set集合存为索引以提供排序</td>
</tr>
<tr>
<td>NumericDocValuesField</td>
<td>Long类型存为索引以提供排序</td>
</tr>
<tr>
<td>SortedNumericDocValuesField</td>
<td>Long类型的set集合存为索引以提供排序</td>
</tr>
<tr>
<td>StoredField</td>
<td>只存储值，不创建索引。注：SortedDocValuesField、SortedSetDocValuesField、NumericDocValuesField、SortedNumericDocValuesField使用时若需要结果中显示排序值，则需要实例化同一个字段的StoredField</td>
</tr>
</tbody></table>
<h2 id="查询索引"><a href="#查询索引" class="headerlink" title="查询索引"></a>查询索引</h2><p>lucene读取索引，根据指定的Query，或者BooleanQuery(多条件)等查询出结果根据得分情况排序。</p>
<pre><code>//创建索引读取对象
IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(luceneIndexPath, new String[0])));
//创建索引查找对象
IndexSearcher searcher = new IndexSearcher(reader);
//创建基础查询单元
Term term = new Term(&quot;sign&quot;,&quot;萌&quot;);
//创建查询
TermQuery query = new TermQuery(term);
//查询 第二个参数代表查询得分高的前3个
TopDocs search = searcher.search(query, 3);
//得到命中
ScoreDoc[] hits = search.scoreDocs;
if(hits.length &gt; 0)&#123;
    for(ScoreDoc sd : hits)&#123;
        Document doc = searcher.doc(sd.doc);
        System.out.println(&quot;id:&quot;+ doc.get(&quot;id&quot;) +&quot;,name:&quot;+ doc.get(&quot;name&quot;) +&quot;,sign:&quot;+  doc.get(&quot;sign&quot;));
    &#125;
&#125;
</code></pre>
<h4 id="多条件查询"><a href="#多条件查询" class="headerlink" title="多条件查询"></a>多条件查询</h4><pre><code>//创建官方中文分词器
SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer();
//创建一个查询解析器
QueryParser parser = new QueryParser(&quot;sign&quot;, analyzer);
//解析传入的查询内容 例如我家 -&gt; sign:我，sign:家，如果只是TermQuery则不进行分析解析sign:我家
Query query = parser.parse(&quot;我家&quot;);
//创建BooleanClause
BooleanClause c1 = new BooleanClause(new TermQuery(new Term(&quot;name&quot;, &quot;大&quot;)), Occur.SHOULD);
BooleanClause c2 = new BooleanClause(query, Occur.SHOULD);
//添加查询条件到查询器中
BooleanQuery booleanQuery = new BooleanQuery.Builder().add(c1).add(c2).build();

TopDocs search = searcher.search(booleanQuery, 3);
</code></pre>
<h4 id="Occur类说明"><a href="#Occur类说明" class="headerlink" title="Occur类说明"></a>Occur类说明</h4><table>
<thead>
<tr>
<th>名称</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>Occur.FILTER</td>
<td>类似MUST，除非这些条件不参与计分</td>
</tr>
<tr>
<td>Occur.MUST</td>
<td>条件必须出现在匹配结果中</td>
</tr>
<tr>
<td>Occur.MUST_NOT</td>
<td>条件必须不出现在匹配结果中</td>
</tr>
<tr>
<td>Occur.SHOULD</td>
<td>条件应该出现在结果中，但不是必须的</td>
</tr>
</tbody></table>
<h4 id="排序"><a href="#排序" class="headerlink" title="排序"></a>排序</h4><p>如果需要排序，则在创建索引的时候如下设置</p>
<pre><code>//存入索引，但是并未存入值
doc.add(new IntPoint(&quot;sort&quot;, 1));
//添加排序
doc.add(new NumericDocValuesField(&quot;sort&quot;, 1));
//只存储值，不然结果集无法出现
doc.add(new StoredField(&quot;sort&quot;, 1));  
</code></pre>
<p>查询时则</p>
<pre><code>//排序的字段为sort，类型为int，false == asc,true == desc
SortField sortField = new SortField(&quot;sort&quot;, SortField.Type.INT, false);
Sort sort = new Sort(sortField);
TopDocs results = searcher.search(query, 3, sort);
</code></pre>
<h4 id="高亮显示"><a href="#高亮显示" class="headerlink" title="高亮显示"></a>高亮显示</h4><pre><code>//创建一个高亮类，传入的SimpleHTMLFormatter默认为给匹配处添加&lt;B&gt;&lt;/B&gt;标签，query就是searcher.search(query, 3)中的同一个query
//另一个构造器Highlighter(&quot;&lt;i&gt;&quot;,&quot;&lt;i/&gt;&quot;);
Highlighter highlighter = new Highlighter(new SimpleHTMLFormatter(),new QueryScorer(query));
//设置最多返回多少匹配片段
highlighter.setTextFragmenter(new SimpleFragmenter(20));
//得到高亮的串
String sign = highlighter.getBestFragment(analyzer, &quot;sign&quot;, doc.get(&quot;sign&quot;));
</code></pre>
<p>以上是本小菜的学习总结，若有错误，请大佬指教！</p>

  </article>
  
</article>


    </div>
  </div>
  <footer>
  
  
  <p>
    Powered by <a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a> | Theme <a target="_blank" rel="noopener" href="https://github.com/syy11cn/hexo-theme-linear">Linear</a> from <a target="_blank" rel="noopener" href="https://syy11.cn">Yiyang Sun</a>
  </p>
</footer>
  
  <script src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
  </script>
  <script>
    Waline({
      el: '#waline',
      placeholder: '',
      avatar: 'retro',
      visitor: true,
      requiredFields: ['nick', 'mail'],
      serverURL: '',
      emoji: [
        'https://cdn.jsdelivr.net/gh/walinejs/emojis@1.0.0/bilibili',
        'https://cdn.jsdelivr.net/gh/walinejs/emojis@1.0.0/qq',
        'https://cdn.jsdelivr.net/gh/walinejs/emojis@1.0.0/alus',
        'https://cdn.jsdelivr.net/gh/walinejs/emojis@1.0.0/tw-emoji',
        'https://cdn.jsdelivr.net/gh/walinejs/emojis@1.0.0/weibo',
        'https://cdn.jsdelivr.net/gh/walinejs/emojis@1.0.0/tieba',
      ]
    });
  </script>
</body>

</html>